<?php 

namespace app\admin;

use think\App;

class BaseController extends \app\BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 页数
     * @var int
     */
    protected $page = 1;

    /**
     * 页码
     * @var int
     */
    protected $pagesize = 10;

    /**
     * @var array
     */
    protected $appletId = 1;

    /**
     * @var array
     */
    protected $post = [];

    /**
     * @var array
     */
    protected $get = [];

    /**
     * @var null
     */
    protected $admin = null;

    /**
     * @var null
     */
    protected $token = null;

	public function __construct(App $app)
	{
		parent::__construct($app);
		$this->initialize();
	}

	public function initialize()
	{
		$this->page = $this->request->get('page')?:1;

        $this->pagesize = $this->request->get('pagesize')?:10;

        $this->post = $this->request->post();

        $this->get = $this->request->get();

        $this->appletId = $this->request->header('AppletId')?:1;

        $authHeader = $this->request->header('Authorization');
        if (!empty($authHeader) && preg_match("/^Bearer\\s+(.*?)$/", $authHeader, $matches)) {
            $token = $matches[1];
        } else {
            $token = $this->request->get("token", "string", null);
        }

    //     //检查TOKEN
        if ($token && $admin = $this->app->adminService->checkToken($token)) {
            $this->token = $token;
            $this->admin = $admin;
        }
    //     //检查是否需要登录
        $this->invokeLogin();
	}

    protected function invokeLogin()
    {
        $noLogin = [
            'admin' => ['login']
        ];

        $controller = $this->request->controller(true);

        $action = $this->request->action(true);

        if(!isset($noLogin[$controller]) || !in_array($action, $noLogin[$controller])) {
            if (!$this->admin) {
                echo json_encode(['code' => 401, 'msg' => '请先登录', 'data' => []], JSON_UNESCAPED_UNICODE);exit;
            }
        }
    }

}